package com.imooc.bilibili.service.impl;

import com.imooc.bilibili.dao.FileInfoDao;
import com.imooc.bilibili.entity.FileInfo;
import com.imooc.bilibili.service.FileService;
import com.imooc.bilibili.utils.FastDFSUtils;
import com.imooc.bilibili.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;

@Service("fileService")
public class FileServiceImpl implements FileService {

    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private FastDFSUtils dfsUtils;

    public String uploadFileBySlices(MultipartFile slices,
                                     String fileMD5,
                                     Integer sliceNo,
                                     Integer totalSliceNo) throws IOException {
        FileInfo dbFileMD5 = fileInfoDao.getFileByMD5(fileMD5);
        if (null != dbFileMD5) {
            return dbFileMD5.getFileUrl();
        }
        String url = dfsUtils.uploadFileBySlices(slices,fileMD5,sliceNo,totalSliceNo);
        if (StringUtils.isNotBlank(url)) {
            dbFileMD5 = new FileInfo();
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            dbFileMD5.setFileUrl(url);
            dbFileMD5.setFileType(dfsUtils.getFileType(slices));
            dbFileMD5.setFileLogo(fileMD5);
            dbFileMD5.setEnableState(0);
            dbFileMD5.setDeleteState(0);
            dbFileMD5.setCreateTime(timestamp);
            dbFileMD5.setUpdateTime(timestamp);
            fileInfoDao.insert(dbFileMD5);
        }
        return url;
    }

    public String getFileMD5(MultipartFile file) throws IOException {
        return MD5Utils.getFIleMD5(file);
    }
}
